package demo6;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 0; i < n; ) {
            for (int j = i + 1; j < n; ) {
                int left = j + 1, right = n -1;
                while (left < right) {
                    long aim = (long)target - nums[i] - nums[j];
                    if (nums[left] + nums[right] < aim) {
                        left++;
                    }else if (nums[left] + nums[right] > aim) {
                        right--;
                    }else {
                        ret.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[j], nums[left], nums[right])));
                        left++; right--;
                        while (left < right && nums[left] == nums[left - 1]) left++;
                        while (left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                j++;
                while (j < n && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while (i < n && nums[i] == nums[i - 1]) i++;
        }
        return ret;
    }

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 0; i < nums.length;) {
            int left = i + 1, right = nums.length - 1;
            int target = -nums[i];
            while (left < right) {
                if (nums[left] + nums[right] < target) {
                    left++;
                }else if(nums[left] + nums[right] > target) {
                    right--;
                }else {
                    ret.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left], nums[right])));
                    left++; right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                }
            }
            i++; //去重i
            while (i < nums.length && nums[i] == nums[i - 1]) i++;
        }
        return ret;
    }
}
